package com.rongke.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.rongke.commons.FailException;
import com.rongke.commons.JsonCodeEnum;
import com.rongke.enums.MemberLevelEnum;
import com.rongke.enums.UserTypeEnum;
import com.rongke.mapper.MuserMapper;
import com.rongke.mapper.SystemParmMapper;
import com.rongke.model.Muser;
import com.rongke.model.SystemParm;
import com.rongke.redis.CacheUtil;
import com.rongke.service.MuserService;
import com.rongke.utils.Md5;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.eis.SessionDAO;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.subject.support.DefaultSubjectContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * @MuserServiceImpl
 * @ServiceImpl
 * @version : Ver 1.0
 */
@Service
public class MuserServiceImpl extends ServiceImpl<MuserMapper, Muser> implements MuserService {

    @Autowired
    private MuserMapper muserMapper;
    @Autowired
    private SessionDAO sessionDAO;
    @Autowired
    private SystemParmMapper systemParmMapper;
    @Autowired
    private CacheUtil cacheUtil;

    @Override
    public List<Muser> selectTeamListByUserId(String userId) {
        return muserMapper.selectTeamListByUserId(userId);
    }

    /**
     *
     * @param token  登录令牌
     *  剔除用户
     */
    @Override
    public void kickOutUser(UsernamePasswordToken token) {
        String loginName = token.getUsername();
        Collection<Session> sessions = sessionDAO.getActiveSessions();
        for(Session session:sessions){
            if (session.getTimeout()==0) {
                sessionDAO.delete(session);
            }
            if(loginName.equals(String.valueOf(session.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY)))) {
                //设置session立即失效，即将其踢出系统
                session.setTimeout(0);
                logout();
            }
        }
    }

    @Override
    public String getReturnRate(int level) {
        String reternMiduoduo="";
        switch (level){
            case 1:
                reternMiduoduo=MemberLevelEnum.MBLEVEL1.getMdValue();
             break;
            case 2:
                reternMiduoduo=MemberLevelEnum.MBLEVEL2.getMdValue();
            break;
            case 3:
                reternMiduoduo=MemberLevelEnum.MBLEVEL3.getMdValue();
            break;
            case 4:
                reternMiduoduo=MemberLevelEnum.MBLEVEL4.getMdValue();
            break;
            case 5:
                reternMiduoduo=MemberLevelEnum.MBLEVEL5.getMdValue();
            break;
        }
        if("".equals(reternMiduoduo) ){
            return null;
        }
       String str=reternMiduoduo;
        return str;
    }

    @Override
    public Integer findUserTotalTeamSize(long id) {
        EntityWrapper<Muser> ew=new EntityWrapper<>();
        ew.where(" find_in_set("+id+",muser.recommend_user_ids) >0",null);
        Integer num=muserMapper.selectCount(ew);
        return num;
    }

    @Override
    public Muser findFirstRecomendUser(Long userId,Integer type) {
        String recomendId;
        Muser muser1=null;
        //如果缓存中有直接从缓存中获取第一个推荐人身份为百夫长或内部员工的id
        if(type== UserTypeEnum.CENTURION.getType()){
            if(cacheUtil.hasKey("centurion"+userId)){
                recomendId=cacheUtil.getString("centurion"+userId);
                muser1=muserMapper.selectById(recomendId);
                return muser1;
            }
        }else if(type== UserTypeEnum.ChIEFCOMMANDER.getType()){
            //如果缓存中有直接从缓存中获取第一个推荐人身份为千夫长的id
            if(cacheUtil.hasKey("chiefComander"+userId)){
                recomendId=cacheUtil.getString("chiefComander"+userId);
                muser1=muserMapper.selectById(recomendId);
                return muser1;
            }
        }else if(type== UserTypeEnum.FRANCHISEE.getType()){
            //如果缓存中有直接从缓存中获取第一个推荐人身份为千夫长的id
            if(cacheUtil.hasKey("franchisee"+userId)){
                recomendId=cacheUtil.getString("franchisee"+userId);
                muser1=muserMapper.selectById(recomendId);
                return muser1;
            }
        }
            Muser muser=muserMapper.selectById(userId);
            String recomendIds=muser.getRecommendUserIds();
            int num=-1;
            if(recomendIds==null){
                return  null;
            }
            List<String> ids= Arrays.asList(recomendIds.split(","));
            EntityWrapper<Muser> ew=new EntityWrapper<>();
            ew.in("id",ids);
            if(type== UserTypeEnum.CENTURION.getType()){
                ew.in("user_type",Arrays.asList("2","4"));
            }else if(type== UserTypeEnum.ChIEFCOMMANDER.getType()){
                ew.eq("user_type",5);
            }else if(type== UserTypeEnum.FRANCHISEE.getType()){
                ew.eq("user_type",6);
            }
            List<Muser> musers =muserMapper.selectList(ew);
            if(musers.isEmpty()){
                return null;
            }else {
                int i=1,y=musers.size();
                recomendId=String.valueOf(musers.get(0).getId());
                num=recomendIds.indexOf(recomendId);
                for(;i<y;i++){
                    int num2=recomendIds.indexOf(String.valueOf(musers.get(i).getId()));
                    if(num2<num){
                        num=num2;
                        recomendId=String.valueOf(musers.get(i).getId());
                    }
                }
            }
            if(num==-1){
                return null;
            }
            muser1=muserMapper.selectById(recomendId);
        if(type== UserTypeEnum.CENTURION.getType()){
            cacheUtil.put("centurion"+userId,recomendId);
        }else if(type== UserTypeEnum.ChIEFCOMMANDER.getType()){
            cacheUtil.put("chiefComander"+userId,recomendId);
        }else if(type== UserTypeEnum.FRANCHISEE.getType()){
            cacheUtil.put("franchisee"+userId,recomendId);
        }
        return muser1;
    }



    /**
     * 退出登录
     */
    public void logout() {
        Subject subject = SecurityUtils.getSubject();
        if (subject.isAuthenticated()) {
            // session 会销毁，在SessionListener监听session销毁，清理权限缓存
            subject.logout();
        }
    }

    public  static  void  main(String str[]){
        String salt="7r^st1_9se13u";
        String str1="machineCode="+"00000003"+"&phone="+"18337102204"+salt;
        String resultString= Md5.md5Encode(str1);
        System.out.print(resultString);

    }


    /**
     * 获取当前登陆用户
     * @return JsonResp
     */
    public Muser findLoginUser() {
        Subject subject = SecurityUtils.getSubject();
        PrincipalCollection collection = subject.getPrincipals();
        if (null != collection && !collection.isEmpty()) {
            String phone = (String) collection.iterator().next();
            Muser muser1=new Muser();
            muser1.setPhone(phone);
            Muser user = muserMapper.selectOne(muser1);
            return user;
        }
        throw new FailException(JsonCodeEnum.OVERTIME.getMessage());
    }

    @Override
    public Double findProfitability(Long userId) {
        Muser muser=muserMapper.selectById(userId);
        Double profitability=null;
        Integer userType=muser.getUserType();
        if(userType==UserTypeEnum.INTERNALSTAFF.getType()){
            if(muser.getProfitability()!=null){
                profitability=muser.getProfitability();
            }
        }else {
            List<SystemParm> systemParms=systemParmMapper.selectList(null);
            if(userType==UserTypeEnum.CENTURION.getType()){
                profitability=systemParms.get(0).getCenturionRate();
            }else if(userType==UserTypeEnum.ChIEFCOMMANDER.getType()){
                profitability=systemParms.get(0).getChiliarchRate();
            }else if(userType==UserTypeEnum.FRANCHISEE.getType()){
                profitability=systemParms.get(0).getFranchiseeRate();
            }
        }
        return profitability;
    }

    @Override
    public Integer getMuserLevel(BigDecimal totalMoney) {
        if(totalMoney.compareTo(new BigDecimal("20000"))<0){
            return MemberLevelEnum.MBLEVEL1.getType();
        } else if(totalMoney.compareTo(new BigDecimal("20000"))>=0 && totalMoney.compareTo(new BigDecimal("50000"))<0){
            return MemberLevelEnum.MBLEVEL2.getType();
        }else if(totalMoney.compareTo(new BigDecimal("50000"))>=0 && totalMoney.compareTo(new BigDecimal("100000"))<0){
            return MemberLevelEnum.MBLEVEL3.getType();
        }else if(totalMoney.compareTo(new BigDecimal("100000"))>=0 && totalMoney.compareTo(new BigDecimal("200000"))<0){
            return MemberLevelEnum.MBLEVEL4.getType();
        }else{
            return MemberLevelEnum.MBLEVEL5.getType();
        }
    }

    @Override
    public Integer selectPurchaseFrequencyByUserId(Long id) {
        return muserMapper.selectPurchaseFrequencyByUserId(id);
    }

    @Override
    public Integer selectPurchaseFrequencyGEANumber(Map map) {
        return muserMapper.selectPurchaseFrequencyGEANumber(map);
    }


}
